package org.jeecg.modules.bid.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.bid.dto.BidQueryRequest;
import org.jeecg.modules.bid.entity.Bid;
import org.jeecg.modules.bid.entity.BidManagement;
import org.jeecg.modules.bid.entity.BidRecord;
import org.jeecg.modules.bid.service.IBidManagementService;
import org.jeecg.modules.bid.service.IBidRecordService;
import org.jeecg.modules.bid.service.IBidService;
import org.jeecg.modules.bid.vo.BidManagementVO;
import org.jeecg.modules.bid.vo.BidSubmitVO;
import org.jeecg.modules.file.entity.ProcurementFile;
import org.jeecg.modules.file.service.IProcurementFileService;
import org.jeecg.modules.purchase.entity.PurchasePlan;
import org.jeecg.modules.supplier.entity.ProcUserSupplierRelation;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.service.IProcUserSupplierRelationService;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Api(tags = "投标管理22")
@RestController
@RequestMapping("/procurement/bid")
@Slf4j
public class BidController extends JeecgController<Bid, IBidService> {
    @Autowired
    public IBidService bidService;

    @Autowired
    private ISupplierService supplierService;

    @Autowired
    private IProcUserSupplierRelationService procUserSupplierRelationService;

    @Autowired
    private IProcurementFileService procurementFileService;
    @Autowired
    private IBidRecordService bidRecordService;
    @Autowired
    private IBidManagementService bidManagementService;


    @AutoLog(value = "投标-分页列表查询-管理")
    @ApiOperation(value = "投标-分页列表查询", notes = "投标-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryList(@RequestParam(defaultValue = "1") Integer pageNo,
                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Page<BidManagement> page = new Page<>(pageNo, pageSize);
            // 创建查询条件，避免查询所有字段时可能出现的问题
            QueryWrapper<BidManagement> queryWrapper = new QueryWrapper<>();
            // 按创建时间降序排序，最新的在前面
            queryWrapper.orderByDesc("create_time");
            page = bidManagementService.page(page, queryWrapper);
            if (page.getTotal() == 0) {
                return Result.OK("未查询到评价", page);
            }
            return Result.OK(page);
        } catch (Exception e) {
            log.error("查询投标列表失败", e);
            return Result.error("查询失败，请稍后重试");
        }
    }

    //通过id查询BidManagement
    @AutoLog(value = "投标-通过id查询投标-管理")
    @ApiOperation(value = "投标-通过id查询投标（管理）", notes = "投标-通过id查询投标（管理）")
    @GetMapping(value = "/getById")
    public Result<?> getById(@RequestParam(name = "id", required = true) String id) {
        // 调用服务层方法获取投标管理详情
        BidManagementVO bidManagementVo = bidManagementService.getBidManagementDetailById(id);

        if (bidManagementVo == null) {
            return Result.error("未查询到投标记录");
        }

        return Result.OK(bidManagementVo);
    }


    //编辑投标
    @AutoLog(value = "投标-编辑/报价2")
    @ApiOperation(value = "投标-报价-用户", notes = "投标-报价-用户")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BidSubmitVO bidSubmitVO) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 检查投标记录是否存在
        Bid bid = bidService.getById(bidSubmitVO.getId());
        if (bid == null) {
            return Result.error("投标记录不存在");
        }

        bid.setBidDescription(bidSubmitVO.getBidDescription());
        bid.setBidPrice(bidSubmitVO.getBidPrice());
        bid.setBidStatus(bidSubmitVO.getBidStatus());
        bid.setUpdateBy(sysUser.getUsername());
        bid.setUpdateTime(new Date());

        if(bidService.updateById(bid)){
            BidRecord bidRecord = new BidRecord();
            bidRecord.setBidId(bid.getId());
            bidRecord.setBidTime(bid.getCreateTime());
            bidRecord.setBidPrice(bid.getBidPrice());
            bidRecord.setStatus(bid.getBidStatus());
            bidRecord.setSupplierId(bid.getSupplierId());
            bidRecord.setPurchaseId(bid.getPurchaseId());
            int Remark = bidRecordService.countByPurchaseIdAndSupplierId(bid.getPurchaseId(), bid.getId())+1;
            bidRecord.setRemark("第 "+ Remark+" 次报价");
            bidRecordService.save(bidRecord);
            return Result.OK("编辑成功");
        }

        return Result.error("编辑失败");
    }



    @AutoLog(value = "投标-报名/投标-用户")
    @ApiOperation(value = "投标-报名/投标-用户", notes = "投标-报名-用户")
    @PostMapping(value = "/register")
    public Result<?> register(@RequestParam(name = "id", required = true) String id) {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Bid existingBid = bidService.getById(id);
        if (existingBid == null) {
            return Result.error("投标记录不存在");
        }
        existingBid.setBidStatus("1");
        existingBid.setUpdateBy(sysUser.getUsername());
        existingBid.setUpdateTime(new Date());
        if (bidService.updateById(existingBid)) {
            return Result.OK("投标-报名成功");
        } else {
            return Result.error("投标-报名失败");
        }
    }

    //供应商放弃报名
    @AutoLog(value = "投标-放弃报名成功-用户")
    @ApiOperation(value = "投标-放弃报名成功-用户", notes = "投标-放弃报名成功")
    @PostMapping(value = "/cancelregister")
    public Result<?> cancelregister(@RequestParam(name = "id", required = true) String id) {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            //抽签中的供应商可以不报名
            Bid existingBid = bidService.getById(id);
            if (existingBid == null) {
                return Result.error("投标记录不存在");
            }

            existingBid.setBidStatus("3");
            existingBid.setUpdateBy(sysUser.getUsername());
            existingBid.setUpdateTime(new Date());
            if (bidService.updateById(existingBid)) {
                return Result.OK("投标-放弃报名成功");
            } else {
                return Result.error("投标-放弃报名成功");
            }
        } catch (Exception e) {
            log.error("投标-放弃报名成功", e);
            return Result.error("投标-放弃报名成功：" + e.getMessage());
        }
    }
    @AutoLog(value = "投标-已完成-管理")
    @ApiOperation(value = "投标-已完成-管理", notes = "投标-已完成-管理")
    @PostMapping(value = "/markascompleted")
    public Result<?> markAsCompleted(@RequestParam(name = "id", required = true) String id) {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        boolean success = bidManagementService.markAsCompleted(id, sysUser.getUsername());
        if (success) {
            return Result.OK("投标已完成");
        } else {
            return Result.error("投标记录不存在或更新失败");
        }
    }
    //根据投标状态查看供应商列表
    @AutoLog(value = "投标-根据投标状态查看供应商列表")
    @ApiOperation(value = "投标-根据投标状态查看供应商列表", notes = "投标-根据投标状态查看供应商列表")
    @PostMapping(value = "/viewbidstatus")
    public Result<?> viewbidstatus(@RequestParam(name = "bidStatus", required = true) String bidStatus) {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            List<Supplier> supplierList = bidService.getSuppliersByBidStatus( bidStatus);
            if (supplierList != null && !supplierList.isEmpty()) {
                return Result.OK(supplierList);
            } else {
                return Result.OK("未找到符合条件的供应商");
            }
        } catch (Exception e) {
            log.error("投标-根据投标状态查看供应商列表失败", e);
            return Result.error("投标-根据投标状态查看供应商列表失败：" + e.getMessage());
        }
    }



    //获取中标状态列表
    @AutoLog(value = "投标-获取中标状态列表")
    @ApiOperation(value = "投标-获取中标状态列表", notes = "投标-获取中标状态列表")
    @PostMapping(value = "/bidstatus")
    public Result<?> bidstatus(@RequestParam(name = "is_winning", required = true) String isWinning) {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        try {
            List<Bid> BidList = bidService.bidstatus(isWinning);
            if (BidList != null && !BidList.isEmpty()) {
                return Result.OK(BidList);
            } else {
                return Result.error("未找到符合条件的供应商");
            }
        } catch (Exception e) {
            log.error("投标-查看供应商列表失败", e);
            return Result.error("投标-根据供应商查看可投标列表失败：" + e.getMessage());
        }
    }

    //该项目选择最低报价的供应商（中标）
    @AutoLog(value = "投标-该项目选择最低报价的供应商（中标）")
    @ApiOperation(value = "投标-该项目选择最低报价的供应商（中标）", notes = "投标-该项目选择最低报价的供应商（中标）")
    @PostMapping(value = "/selectwinner")
    public Result<?> selectwinner(@RequestParam(name = "purchaseId", required = true) String purchaseId) {
        try {
            // 获取当前登录用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (sysUser == null) {
                return Result.error("用户未登录");
            }

            // 调用服务层方法选择中标供应商
            boolean result = bidService.selectWinner(purchaseId, sysUser.getUsername());

            if (result) {
                return Result.OK("投标-该项目选择最低报价的供应商（中标）成功");
            } else {
                return Result.error("投标-该项目选择最低报价的供应商（中标）失败：更新数据失败");
            }
        } catch (Exception e) {
            log.error("投标-该项目选择最低报价的供应商（中标）失败", e);
            return Result.error("投标-该项目选择最低报价的供应商（中标）失败：" + e.getMessage());
        }
    }
    //根据供应商在proc_bid表中找，返回列表
    @AutoLog(value = "投标-根据供应商查看可投标列表")
    @ApiOperation(value = "投标-根据供应商查看可投标列表", notes = "投标-根据供应商查看可投标列表")
    @PostMapping(value = "/viewsupplier")
    public Result<?> viewsupplier(@RequestParam(name = "bidStatus", required = true) String bidStatus) {
        // 获取当前登录用户
          LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            ProcUserSupplierRelation relationBySearchKey = procUserSupplierRelationService.getRelationBySearchKey(sysUser.getId());
            if(relationBySearchKey == null) return Result.error("供应商未绑定用户");
            List<Bid> LotteryList = bidService.getSuppliers(relationBySearchKey.getSupplierId(),bidStatus);
            if (LotteryList != null && !LotteryList.isEmpty()) {
                return Result.OK(LotteryList);
            } else {
                return Result.error("未找到符合条件的供应商");
            }
        } catch (Exception e) {
            log.error("投标-查看供应商列表失败", e);
            return Result.error("投标-根据供应商查看可投标列表失败：" + e.getMessage());
        }
    }

    //通过id查询投标记录
    @AutoLog(value = "投标-通过id查询投标3(用户)")
    @ApiOperation(value = "投标-通过id查询投标(用户)", notes = "投标-通过id查询投标(用户)")
    @PostMapping(value = "/viewbid")
    public Result<?> viewbid(@RequestParam(name = "id", required = true) String id) {
        // 获取当前登录用户
         LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            Bid bid = bidService.getById(id);
            if (bid != null) {
                BidSubmitVO bidSubmitVO =new BidSubmitVO();
                BeanUtils.copyProperties(bid, bidSubmitVO);

                List<ProcurementFile> file = procurementFileService.getFilesByBiz(id,"bid");
                bidSubmitVO.setBidDocument(file);
                return Result.OK(bidSubmitVO);
            } else {
                return Result.error("未找到符合条件的投标记录");
            }
        } catch (Exception e) {
            log.error("投标-通过id查询投标记录失败", e);
            return Result.error("投标-通过id查询投标记录失败：" + e.getMessage());
        }
    }
    //通过用户的client_id得知对应的supplierId，查找proc_bid表中对应supplierId并显示
    @AutoLog(value = "投标-通过当前用户查询投标列表")
    @ApiOperation(value="投标-通过当前用户查询投标记录", notes="投标-通过当前用户查询投标记录")
    @GetMapping(value = "/getMyBids")
    public Result<?> getMyBids(@RequestParam(defaultValue = "1") Integer pageNo,
                               @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            // 获取当前登录用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (sysUser == null) {
                return Result.error("用户未登录");
            }

            // 获取用户的client_id作为supplierId
            ProcUserSupplierRelation procUserSupplierRelation= procUserSupplierRelationService.getRelationBySearchKey(sysUser.getId());
            String supplierId = procUserSupplierRelation.getSupplierId();
            if (supplierId == null) {
                return Result.error("用户未关联供应商信息");
            }

            // 调用服务层方法查询数据，添加按创建时间降序排序
            QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("supplier_id", supplierId);
            queryWrapper.orderByDesc("create_time");

            Page<Bid> page = new Page<>(pageNo, pageSize);
            Page<Bid> pageList = bidService.page(page, queryWrapper);

            return Result.OK(pageList);
        } catch (Exception e) {
            log.error("投标-通过当前用户查询投标记录失败", e);
            return Result.error("投标-通过当前用户查询投标记录失败：" + e.getMessage());
        }
    }

    @AutoLog(value = "投标-模糊查询")
    @ApiOperation(value = "投标-模糊查询", notes = "投标-模糊查询")
    @GetMapping(value = "/getBidPageBysearch")
    public Result<?> getBidPageBysearch(BidQueryRequest queryRequest) {
        // 如果queryRequest为null，创建默认实例
        if (queryRequest == null) {
            queryRequest = new BidQueryRequest();
        }

        // 设置默认分页参数
        if (queryRequest.getPageNum() == null || queryRequest.getPageNum() <= 0) {
            queryRequest.setPageNum(1);
        }
        if (queryRequest.getPageSize() == null || queryRequest.getPageSize() <= 0) {
            queryRequest.setPageSize(10);
        }
        // 创建查询条件
        Page<Bid> page = new Page<>(queryRequest.getPageNum(), queryRequest.getPageSize());
        QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
        // 按投标状态查询
        if (queryRequest.getBidStatus() != null && !queryRequest.getBidStatus().isEmpty()) {
            queryWrapper.eq("bid_status", queryRequest.getBidStatus());
        }
        // 按项目名称查询
        if (queryRequest.getProjectName() != null && !queryRequest.getProjectName().isEmpty()) {
            queryWrapper.like("project_name", queryRequest.getProjectName());
        }
        //使用前端传入的供应商名称，到供应商表中查询可能的supplierId
        if (queryRequest.getSupplierName() != null && !queryRequest.getSupplierName().isEmpty()) {
            List<String> supplierIds = supplierService.getSupplierIdByName(queryRequest.getSupplierName());
            queryWrapper.in("supplier_id", supplierIds);
        }
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        try {
            Page<Bid> BidPageList = bidService.page(page, queryWrapper);
            if (page.getTotal() == 0) {
                return Result.OK("未查询到符合条件的投标记录", BidPageList);
            }
            return Result.OK(BidPageList);
        } catch (Exception e) {
            log.error("查询投标记录失败", e);
            return Result.error("查询投标记录失败：" + e.getMessage());
        }
    }

    @AutoLog(value = "中标列表")
    @ApiOperation(value = "投标-中标列表", notes = "投标-中标列表")
    @GetMapping(value = "/listbid")
    public Result<?> listbid(@RequestParam(defaultValue = "1") Integer pageNo,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ProcUserSupplierRelation procUserSupplierRelation= procUserSupplierRelationService.getRelationBySearchKey(sysUser.getId());

            QueryWrapper<Bid> bidQueryWrapper = new QueryWrapper<>();
            bidQueryWrapper.eq("supplier_id", procUserSupplierRelation.getSupplierId());
            bidQueryWrapper.orderByDesc("create_time");
            List<Bid> winningBids = bidService.list(bidQueryWrapper);;
            // 调用服务层方法查询数据，添加按创建时间降序排序
            // 从中标记录中提取purchaseId进行查询
            List<String> purchaseIds = winningBids.stream()
                    .map(Bid::getPurchaseId)
                    .filter(id -> id != null && !id.isEmpty())
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());

            if (org.springframework.util.CollectionUtils.isEmpty(purchaseIds)) {
                Page<BidManagement> emptyPage = new Page<>(pageNo, pageSize);
                return Result.OK("暂无中标记录", emptyPage);
            }
            // 根据中标记录构建查询条件
            QueryWrapper<BidManagement> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("purchase_id", purchaseIds);
            queryWrapper.orderByDesc("create_time");

            Page<BidManagement> page = new Page<>(pageNo, pageSize);
            Page<BidManagement> bidManagementPage = bidManagementService.page(page, queryWrapper);

            return Result.OK(bidManagementPage);

        } catch (Exception e) {
            log.error("投标-中标列表", e);
            return Result.error("投标-中标列表：" + e.getMessage());
        }
    }

    /**
     * 导出通过ids查询BidManagement，导出excel，导出多条BidManagement
     */
    @AutoLog(value = "投标-批量导出Excel")
    @ApiOperation(value = "投标-批量导出Excel", notes = "投标-批量导出Excel")
    @GetMapping(value = "/exportExcelByIds")
    public void exportExcelByIds(@RequestParam(name = "ids") List<String> ids, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 调用服务层方法导出Excel
            bidManagementService.exportExcelByIds(ids, request, response);
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            // 设置响应状态
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出Excel失败: " + e.getMessage());
            } catch (IOException ioException) {
                log.error("设置响应失败", ioException);
            }
        }
    }
    /**
     * 根据bidId查询投标记录列表
     * @param bidId bidId
     * @return 投标记录列表
     */
    @AutoLog(value = "投标-根据bidId查询")
    @ApiOperation(value = "投标-根据bidId查询", notes = "根据BidID查询投标记录")
    @GetMapping(value = "/getBybidId")
    public Result<?> getBybidId(@RequestParam(name = "bidId", required = true) String bidId) {
        try {
            // 构建查询条件，根据bidId查询proc_bid_record表
            QueryWrapper<BidRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("bid_id", bidId);
            queryWrapper.orderByDesc("bid_time");

            // 使用bidRecordService查询投标记录列表
            List<BidRecord> bidRecordList = bidRecordService.list(queryWrapper);

            return Result.OK(bidRecordList);
        } catch (Exception e) {
            log.error("查询投标记录失败", e);
            return Result.error("查询投标记录失败：" + e.getMessage());
        }
    }
}
